import strSidebarHtml from "./Sidebar.html"; // 使用 raw-loader 加载 HTML 文件
import { DomUtils } from "../../utils/DomUtils"; // 引入 DomUtils 类

export class Sidebar {
  constructor(menuItems) {
    this.menuItems = menuItems || []; // 若 menuItems 为 undefined，将其初始化为空数组
  }

  renderMenuItem(item) {
    const hasChildren = item.children && item.children.length > 0;
    let menuItemHtml = `<li>`;
    if (hasChildren) {
      const collapseId = `collapse-${item.name.replace(/\s/g, "")}`;
      menuItemHtml += `
        <a class="has-arrow" href="#" data-toggle="collapse" data-target="#${collapseId}" aria-expanded="false">
          <i class="${item.icon} big-icon icon-wrap"></i>
          <span class="mini-click-non">${item.name}</span>
        </a>
        <ul class="submenu-angle collapse" id="${collapseId}" aria-expanded="false">
      `;
      item.children.forEach((child) => {
        menuItemHtml += this.renderMenuItem(child);
      });
      menuItemHtml += `</ul>`;
    } else {
      menuItemHtml += `
        <a title="${item.name}" href="${item.path}">
          <i class="${item.icon} sub-icon-mg" aria-hidden="true"></i>
          <span class="mini-sub-pro">${item.name}</span>
        </a>
      `;
    }
    menuItemHtml += `</li>`;
    return menuItemHtml;
  }

  render() {
    let menuHtml = "";
    if (this.menuItems) {
      // 添加空值检查
      this.menuItems.forEach((item) => {
        menuHtml += this.renderMenuItem(item);
      });
    }
    const sidebarHtml = strSidebarHtml.replace("{{menuItems}}", menuHtml);
    return DomUtils.convertToDom(sidebarHtml);
  }
}
